package com.loren.designer.config;

import com.loren.designer.data.properties.DesignerProperties;
import com.loren.designer.web.interceptor.FrontPageInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@AllArgsConstructor
@ConditionalOnProperty(prefix = "designer.front-page", name = "load", havingValue = "true")
public class WebMvcConfig implements WebMvcConfigurer {

    private final DesignerProperties designerProperties;

    private final FrontPageInterceptor frontPageInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(this.designerProperties.getFrontPage().getContext() + "/**")
                .addResourceLocations(this.designerProperties.getFrontPage().getDistPath());
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:" + this.designerProperties.getFrontPage().getContext());
        registry.addViewController(this.designerProperties.getFrontPage().getContext()).setViewName("forward:" + this.designerProperties.getFrontPage().getContext() + "/index.html");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.frontPageInterceptor)
                .addPathPatterns(this.designerProperties.getFrontPage().getContext() + "/**")
                .excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.ico", "/**/*.png", "/**/*.jpg", "/**/*.jpeg", "/**/*.gif", "/**/fonts/*", "/**/*.svg");
    }
}
